	//
	//  RippleWaveView.m
	//  AnimationDemo
	//
	//  Created by Gikki Ares on 2021/4/30.
	//  Copyright © 2021 vgemv. All rights reserved.
	//

#import "UIView+JsAnimation.h"
#import <objc/runtime.h>

@implementation UIView(JsAnimation)

- (void)js_addWaveAnimationWithWaveColor:(UIColor *)waveColor{
	SEL key = @selector(js_addWaveAnimationWithWaveColor:);
	CALayer * animationLayer = objc_getAssociatedObject(self, key);
	if(!animationLayer) {
		NSInteger pulsingCount = 5;
		double animationDuration = 2;
		CGRect rect = self.bounds;
		
		animationLayer = [CALayer layer];
		objc_setAssociatedObject(self, key, animationLayer, OBJC_ASSOCIATION_RETAIN);
		for (int i = 0; i < pulsingCount; i++) {
			CALayer * pulsingLayer = [CALayer layer];
			pulsingLayer.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
			pulsingLayer.borderColor = waveColor.CGColor;
			pulsingLayer.backgroundColor = waveColor.CGColor;
			pulsingLayer.borderWidth = 1;
			pulsingLayer.cornerRadius = rect.size.height / 2;
			
			//在结束点变化缓慢,开始变化比较快
			CAMediaTimingFunction * defaultCurve = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
			
			CAAnimationGroup * animationGroup = [CAAnimationGroup animation];
			animationGroup.fillMode = kCAFillModeBackwards;
			animationGroup.beginTime = CACurrentMediaTime() + (double)i * animationDuration / (double)pulsingCount;
			animationGroup.duration = animationDuration;
			animationGroup.repeatCount = HUGE;
			animationGroup.timingFunction = defaultCurve;
			
			CABasicAnimation * scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
			scaleAnimation.fromValue = @1;
			scaleAnimation.toValue = @3;
			
				//每个时刻对应的opacity的value
			CAKeyframeAnimation * opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
			opacityAnimation.values =   @[@0.8, @0.6, @0.5, @0.4, @0.3, @0.2, @0.1, @0.0];
			opacityAnimation.keyTimes = @[@0.0, @0.2, @0.3, @0.4, @0.5, @0.6, @0.7, @1.0];
			
			
			
			
			animationGroup.animations = @[scaleAnimation, opacityAnimation];
			[pulsingLayer addAnimation:animationGroup forKey:@"plulsing"];
			[animationLayer addSublayer:pulsingLayer];
		}
		[self.layer insertSublayer:animationLayer atIndex:0];
	}
}

- (void)js_removeWaveAnimation {
	SEL key = @selector(js_addWaveAnimationWithWaveColor:);
	CALayer * animationLayer = objc_getAssociatedObject(self, key);
	if(animationLayer) {
		[animationLayer removeFromSuperlayer];
		objc_setAssociatedObject(self, key, nil, OBJC_ASSOCIATION_RETAIN);
	}
}


@end
